{% extends 'dashboard/base.html' %}

{% block title %}{% if food %}编辑菜品 - {{ food.name }}{% else %}添加菜品{% endif %} - 巧巧点餐管理后台{% endblock %}

{% block content %}
<div class="card">
    <div class="card-header">
        <h2 class="card-title">{% if food %}编辑菜品 - {{ food.name }}{% else %}添加菜品{% endif %}</h2>
        <a href="{% url 'dashboard:food_list' %}" class="btn btn-light">
            <i class="fas fa-arrow-left"></i> 返回列表
        </a>
    </div>
    <div class="card-body form-card-body">
        <form method="post" action="{% if food %}{% url 'dashboard:food_edit' food_id=food.id %}{% else %}{% url 'dashboard:food_add' %}{% endif %}" enctype="multipart/form-data">
            {% csrf_token %}
            
            <div class="row">
                <div class="col-md-8">
                    <!-- 左侧：基本信息 -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-info-circle mr-2"></i>基本信息</h5>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="name" class="required">菜品名称</label>
                                <input type="text" id="name" name="name" class="form-control" value="{{ food.name|default:'' }}" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="category" class="required">所属分类</label>
                                <select id="category" name="category" class="form-control" required>
                                    <option value="">请选择分类</option>
                                    {% for category in categories %}
                                    <option value="{{ category.id }}" {% if food and food.category.id == category.id %}selected{% endif %} title="{{ category.name }}">
                                        {{ category.name }}
                                    </option>
                                    {% endfor %}
                                </select>
                                <small class="form-text text-muted">如果需要的分类不存在，请先<a href="{% url 'dashboard:category_add' %}" target="_blank">添加分类</a></small>
                            </div>
                            
                            <div class="form-group">
                                <label for="description">菜品描述</label>
                                <textarea id="description" name="description" class="form-control description" rows="4">{{ food.description|default:'' }}</textarea>
                                <small class="form-text text-muted">详细描述菜品的特点、口味、原料等信息</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-tag mr-2"></i>价格信息</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="price" class="required">售价（亲亲）</label>
                                        <div class="price-input-group">
                                            <input type="number" id="price" name="price" class="form-control" value="{{ food.price|floatformat:'0'|default:'' }}" min="0" step="1" required>
                                        </div>
                                        <small class="form-text text-muted">以亲亲为单位，只能输入整数</small>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="original_price">原价（亲亲）</label>
                                        <div class="price-input-group">
                                            <input type="number" id="original_price" name="original_price" class="form-control" value="{{ food.original_price|floatformat:'0'|default:'' }}" min="0" step="1">
                                        </div>
                                        <small class="form-text text-muted">以亲亲为单位，只能输入整数</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-check-circle mr-2"></i>状态和标签</h5>
                        </div>
                        <div class="card-body">
                            <div class="checkbox-group">
                                <div class="form-check">
                                    <input type="checkbox" id="is_active" name="is_active" class="form-check-input" {% if food.is_active|default:True %}checked{% endif %}>
                                    <label for="is_active" class="form-check-label">上架销售</label>
                                </div>
                                <div class="form-check">
                                    <input type="checkbox" id="is_hot" name="is_hot" class="form-check-input" {% if food.is_hot %}checked{% endif %}>
                                    <label for="is_hot" class="form-check-label">热销商品</label>
                                </div>
                                <div class="form-check">
                                    <input type="checkbox" id="is_new" name="is_new" class="form-check-input" {% if food.is_new %}checked{% endif %}>
                                    <label for="is_new" class="form-check-label">新品上市</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <!-- 右侧：图片上传 -->
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-image mr-2"></i>菜品图片</h5>
                        </div>
                        <div class="card-body">
                            <div class="image-upload-section">
                                <label for="image_file" class="required">上传图片</label>
                                <div class="image-upload-container">
                                    <div class="custom-file-container">
                                        <input type="file" id="image_file" name="image_file" class="form-control-file custom-file-input" accept="image/*">
                                        <div class="custom-file-label">
                                            <i class="fas fa-upload mr-1"></i> 点击此处选择图片...
                                        </div>
                                    </div>
                                    <small class="form-text text-muted my-2">支持JPG、PNG格式，建议尺寸800×600，大小不超过2MB</small>
                                </div>
                                
                                <div class="preview-container">
                                    {% if food.image %}
                                        <img id="image-preview" src="{{ food.image.url }}" alt="预览图" class="img-preview">
                                    {% elif food.image_url %}
                                        <img id="image-preview" src="{{ food.image_url }}" alt="预览图" class="img-preview">
                                    {% else %}
                                        <img id="image-preview" src="/static/dashboard/img/placeholder.jpg" alt="预览图" class="img-preview">
                                    {% endif %}
                                </div>
                            </div>
                            
                            <div class="form-group mt-3">
                                <label for="image_url">或者使用图片URL</label>
                                <input type="text" id="image_url" name="image_url" class="form-control" value="{{ food.image_url|default:'' }}" placeholder="http://...">
                                <small class="form-text text-muted">如果不上传图片文件，可以填写图片URL</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary btn-save">
                    <i class="fas fa-save"></i> 保存菜品
                </button>
                <a href="{% url 'dashboard:food_list' %}" class="btn btn-light ml-2">取消</a>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 图片文件预览
        const imageFileInput = document.getElementById('image_file');
        const imagePreview = document.getElementById('image-preview');
        const fileLabel = document.querySelector('.custom-file-label');
        
        if (imageFileInput && imagePreview) {
            imageFileInput.addEventListener('change', function() {
                if (this.files && this.files[0]) {
                    const file = this.files[0];
                    
                    // 检查文件大小
                    const fileSize = file.size / 1024 / 1024; // 转换为MB
                    if (fileSize > 2) {
                        alert('图片大小不能超过2MB');
                        this.value = '';
                        return;
                    }
                    
                    fileLabel.textContent = file.name;
                    
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        imagePreview.src = e.target.result;
                    };
                    reader.readAsDataURL(file);
                }
            });
        }
        
        // 图片URL预览
        const imageUrlInput = document.getElementById('image_url');
        if (imageUrlInput && imagePreview) {
            imageUrlInput.addEventListener('input', function() {
                if (this.value) {
                    imagePreview.src = this.value;
                } else {
                    // 如果已上传图片文件，则保持图片文件的预览
                    if (imageFileInput.files && imageFileInput.files[0]) {
                        // 保持文件预览
                    } else {
                        imagePreview.src = '/static/dashboard/img/placeholder.jpg';
                    }
                }
            });
        }
        
        // 表单验证
        const form = document.querySelector('form');
        form.addEventListener('submit', function(event) {
            const name = document.getElementById('name').value.trim();
            const category = document.getElementById('category').value;
            const price = document.getElementById('price').value;
            const imageFile = document.getElementById('image_file').files[0];
            const imageUrl = document.getElementById('image_url').value.trim();
            // 检查当前图片预览是否为占位图
            const imagePreview = document.getElementById('image-preview');
            const hasExistingImage = imagePreview && imagePreview.src && 
                                    !imagePreview.src.endsWith('/static/dashboard/img/placeholder.jpg');
            
            let isValid = true;
            let errorMessage = '';
            
            if (!name) {
                errorMessage += '请输入菜品名称\n';
                isValid = false;
            }
            
            if (!category) {
                errorMessage += '请选择所属分类\n';
                isValid = false;
            }
            
            if (!price || price <= 0) {
                errorMessage += '请输入有效的售价\n';
                isValid = false;
            }
            
            // 只有在没有现有图片且没有上传新图片或URL的情况下才提示
            if (!hasExistingImage && !imageFile && !imageUrl) {
                errorMessage += '请上传图片或提供图片URL\n';
                isValid = false;
            }
            
            if (!isValid) {
                event.preventDefault();
                alert('表单验证失败：\n' + errorMessage);
            }
        });
    });
</script>
{% endblock %} 